<?php

namespace App\Http\Controllers\Api;

use App\Logic\Json;
use App\Models\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use XS;

class GoodsController extends Controller
{
    //
    public function index(Request $request)
    {
        header('Access-Control-Allow-Origin:*');

        $query = null;
        $where = [];

        $field = 'id';
        $type  = 'DESC';

        if($request->query->has('choice') && $request->query->get('choice'))
        {
            $choice = explode(',',$request->query->get('choice'));
            $field = $choice[0];
            $type = $choice[1];
        }

        if($request->query->has('platform') && $request->query->get('platform')) $where[] = ['platform' , '=' , $request->query->get('platform')];

        if($request->query->has('name') && $request->query->get('name')) $query = $request->query->get('name');

        if($query)
        {
            //*************
            $xs = new XS(config_path('Xunsearch.ini'));
            $shops = $xs->search->setQuery($query)->setLimit(100)->setDocOrder()->search();
            //*************
            $goodsId = [];
            foreach($shops as $key => $goods)
            {
                $goodsId[] = $goods->pid;
            }

            $apiGoods = Goods::where($where)->whereIn('id', $goodsId)->orderBy($field,$type)->paginate(20);

        }
        else
        {
            $apiGoods = Goods::where($where)->orderBy($field,$type)->paginate(20);
        }

        return Json::success('success',$apiGoods);
    }


}
